package bev.article;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;

import bev.ConnectionManager;
import bev.HelperUtility;

/**
 * Used to store and work with article data about an event in memory.
 */
public class EventArticle extends BaseArticle {
    // Event article data.
    String description, groupsInvolved;
    boolean current, future;
    int year, month, day;

    // Text fields for editing.
    JTextArea txtDescription;
    JTextArea txtGroupsInvolved;
    JComboBox<String> cmbCurrent;
    JComboBox<String> cmbFuture;
    JTextField txtYear;
    JTextField txtMonth;
    JTextField txtDay;

    /**
     * Instantiates a new <i>event</i> article.
     */
    public EventArticle() {
        super();

        // Default values.
        description = "";
        groupsInvolved = "";
        current = false;
        future = false;
        year = 0;
        month = 0;
        day = 0;
    }

    @Override
    public void loadArticle( int id ) {
        id_num = id;

        // Get the results set containing the event.
        try {
            ResultSet rs = ConnectionManager
                    .RunSQLQuery( String
                            .format(
                                    "SELECT id, name, created, updated, description, groupsinvolved, current, future, year, month, day FROM events WHERE id = %d",
                                    id ) );

            if ( rs.next() ) {
                int event_id = rs.getInt( "id" );
                if ( event_id != id ) {
                    System.err.print( "ID from database did not match." );
                    return;
                }

                // Common data.
                name = HelperUtility.stringOrDefault( rs.getString( "name" ) );
                timeCreated = rs.getTimestamp( "created" );
                timeModified = rs.getTimestamp( "updated" );

                // Event data.
                description = HelperUtility.stringOrDefault( rs
                        .getString( "description" ) );
                groupsInvolved = HelperUtility.stringOrDefault( rs
                        .getString( "groupsinvolved" ) );
                current = rs.getBoolean( "current" );
                future = rs.getBoolean( "future" );
                year = rs.getInt( "year" );
                month = rs.getInt( "month" );
                day = rs.getInt( "day" );
            }

            ConnectionManager.closeConnection();
        } catch ( SQLException ex ) {
            ex.printStackTrace();
        } catch ( ClassNotFoundException ex ) {
            ex.printStackTrace();
        }
    }

    @Override
    public void storeArticle() {
        try {
            // Get all the event article IDs from the database.
            ResultSet rs = ConnectionManager
                    .RunSQLQuery( "SELECT id FROM events" );

            // Check if this article's ID exists in database.
            boolean exists = false;
            while ( rs.next() ) {
                int person_id = rs.getInt( "id" );
                if ( person_id == id_num ) {
                    exists = true;
                    break;
                }
            }

            // Update article in database if it exists.
            if ( exists ) {
                int currentint = ( current ? 1 : 0 );
                int futureint = ( future ? 1 : 0 );
                String query = String
                        .format(
                                //                 name,      desc,      groups,    curr,      future,    year,      month,     day
                                "UPDATE events SET %s = '%s', %s = '%s', %s = '%s', %s = '%d', %s = '%d', %s = '%d', %s = '%d', %s = '%d' WHERE id = %d",
                                "name", ConnectionManager.processEscapeChars( name ),
                                "description", ConnectionManager.processEscapeChars( description ),
                                "groupsinvolved", ConnectionManager.processEscapeChars( groupsInvolved ),
                                "current", currentint,
                                "future", futureint,
                                "year", year,
                                "month", month,
                                "day", day,
                                id_num );

                System.out.printf( "Insert query: '%s'\n", query );
                ConnectionManager.RunSQLUpdateQuery( query );
            }
            // Else insert as a new article.
            else {
                int currentint = ( current ? 1 : 0 );
                int futureint = ( future ? 1 : 0 );
                String query = String
                        .format(
                                "INSERT INTO events (name, created, description, groupsinvolved, current, future, year, month, day) VALUES ('%s', '%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')",
                                ConnectionManager.processEscapeChars( name ),
                                HelperUtility.formatDatabaseTimeStamp( timeCreated ),
                                ConnectionManager.processEscapeChars( description ),
                                ConnectionManager.processEscapeChars( groupsInvolved ),
                                currentint, futureint, year, month, day );

                System.out.printf( "Insert query: '%s'\n", query );
                ConnectionManager.RunSQLUpdateQuery( query );
            }

            ConnectionManager.closeConnection();
        } catch ( SQLException ex ) {
            ex.printStackTrace();
        } catch ( ClassNotFoundException ex ) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void addBodyText( JTextPane textPane ) {
        // Description.
        if ( description.length() > 0 ) {
            ArticleFormatter.addSmallHeader( textPane, "Description" );
            ArticleFormatter.addNewLine( textPane, 1 );
            ArticleFormatter.addRegular( textPane, description );
            ArticleFormatter.addNewLine( textPane, 2 );
        }

        // Groups Involved.
        if ( groupsInvolved.length() > 0 ) {
            ArticleFormatter.addSmallHeader( textPane, "Groups Involved" );
            ArticleFormatter.addNewLine( textPane, 1 );
            ArticleFormatter.addRegular( textPane, groupsInvolved );
            ArticleFormatter.addNewLine( textPane, 2 );
        }

        // Current.
        ArticleFormatter.addSmallHeader( textPane, "Current Event: " );
        if ( current == false ) {
            ArticleFormatter.addRegular( textPane, "No" );
        } else {
            ArticleFormatter.addRegular( textPane, "Yes" );
        }
        ArticleFormatter.addNewLine( textPane, 2 );

        // Current.
        ArticleFormatter.addSmallHeader( textPane, "Future Event: " );
        if ( future == false ) {
            ArticleFormatter.addRegular( textPane, "No" );
        } else {
            ArticleFormatter.addRegular( textPane, "Yes" );
        }
        ArticleFormatter.addNewLine( textPane, 2 );

        // Year.
        ArticleFormatter.addSmallHeader( textPane, "Year:\t" );
        ArticleFormatter.addRegular( textPane, String.format( "%d", year ) );
        ArticleFormatter.addNewLine( textPane, 1 );

        // Month.
        ArticleFormatter.addSmallHeader( textPane, "Month:\t" );
        ArticleFormatter.addRegular( textPane, String.format( "%d", month ) );
        ArticleFormatter.addNewLine( textPane, 1 );

        // Day.
        ArticleFormatter.addSmallHeader( textPane, "Day:\t" );
        ArticleFormatter.addRegular( textPane, String.format( "%d", day ) );
        ArticleFormatter.addNewLine( textPane, 1 );
    }

    @Override
    protected JPanel getBodyEditControls() {
        ArticleEditPanel panel = new ArticleEditPanel();

        // Description.
        txtDescription = new JTextArea( description );
        txtDescription.setLineWrap( true );
        JScrollPane spDescription = new JScrollPane( txtDescription );
        spDescription
                .setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED );

        // Location.
        txtGroupsInvolved = new JTextArea( groupsInvolved );
        txtGroupsInvolved.setLineWrap( true );
        JScrollPane spGroupsInvolved = new JScrollPane( txtGroupsInvolved );
        spGroupsInvolved
                .setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED );

        // Current Event combo box.
        Vector<String> yesorno = new Vector<String>();
        yesorno.add( "No" );
        yesorno.add( "Yes" );
        cmbCurrent = new JComboBox<String>( yesorno );
        if ( current == false ) {
            cmbCurrent.setSelectedItem( "No" );
        } else {
            cmbCurrent.setSelectedItem( "Yes" );
        }

        // Future event Event combo box.
        cmbFuture = new JComboBox<String>( yesorno );
        if ( future == false ) {
            cmbFuture.setSelectedItem( "No" );
        } else {
            cmbFuture.setSelectedItem( "Yes" );
        }

        txtYear = new JTextField( String.format( "%d", year ) );
        txtMonth = new JTextField( String.format( "%d", month ) );
        txtDay = new JTextField( String.format( "%d", day ) );

        panel.addComponent( "Description", spDescription );
        panel.addComponent( "Groups Involved", spGroupsInvolved );
        panel.commitComponents();

        panel.addComponent( "Current", cmbCurrent,
                ArticleEditPanel.getSmallFieldSize() );
        panel.addComponent( "Future", cmbFuture,
                ArticleEditPanel.getSmallFieldSize() );
        panel.addComponent( "Year", txtYear,
                ArticleEditPanel.getSmallFieldSize() );
        panel.addComponent( "Month", txtMonth,
                ArticleEditPanel.getSmallFieldSize() );
        panel.addComponent( "Day", txtDay, ArticleEditPanel.getSmallFieldSize() );
        panel.commitComponents();

        return panel;
    }

    @Override
    protected void saveCustomEditData() {
        description = HelperUtility.getTextNullCheck( txtDescription );
        groupsInvolved = HelperUtility.getTextNullCheck( txtGroupsInvolved );
        if ( cmbCurrent.getSelectedItem() == "No" ) {
            current = false;
        } else {
            current = true;
        }
        if ( cmbFuture.getSelectedItem() == "No" ) {
            future = false;
        } else {
            future = true;
        }
        year = HelperUtility.getTextAsIntNullCheck( txtYear );
        month = HelperUtility.getTextAsIntNullCheck( txtMonth );
        day = HelperUtility.getTextAsIntNullCheck( txtDay );

    }

    @Override
    protected boolean validateBodyEditFields() {
        // Year.
        if ( !validateInt( txtYear.getText(), "Year" ) )
            return false;

        // Month.
        if ( !validateInt( txtMonth.getText(), "Month" ) )
            return false;

        // Day.
        if ( !validateInt( txtDay.getText(), "Day" ) )
            return false;

        return true;
    }
}
